<?php
/**
 * Created by PhpStorm.
 * User: Leonly
 * Date: 2015/9/23 0023
 * Time: 13:15
 */

import("WxPay#Api", VENDOR_PATH . 'WxPay', '.php');
import("WxPay#Data", VENDOR_PATH . 'WxPay', '.php');

class WechatAction extends baseAction{
    public static $STATE_LOGIN = 1;
    public static $STATE_REGISTER = 2;

    /**
     * 授权
     * @param int $state
     */
    public static function auth($state = 1) {
        if(! session('?openid')) {
            session('current_url', 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $callback = 'http://'.$_SERVER['HTTP_HOST'] . U('Wechat/oauth_callback');
            $oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".WxPayConfig::APPID."&redirect_uri=".urlencode($callback)."&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
            redirect($oauthUrl);
        }

        return session('openid');
    }

    /**
     * 授权回调
     */
    public function oauth_callback() {
        $code = $_GET['code'];
        $state = $_GET['state'];

        $accessObj = $this->getJSON("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".WxPayConfig::APPID
            ."&secret=".WxPayConfig::APPSECRET."&code=$code&grant_type=authorization_code");

        if(property_exists($accessObj, 'errcode')) {
            $this->error('授权失败：' . $accessObj->errmsg, U('Index/index'));
        }

        $openid = $accessObj->openid;
        session('openid', $openid);

        //获取用户信息
        $Wechat = D('Wechat');
        if(0 == $Wechat->where("openid='$openid'")->count()) {
            $oauthObj = $this->getJSON("https://api.weixin.qq.com/sns/userinfo?access_token=$accessObj->access_token&openid=$openid&lang=zh_CN");
            if(!property_exists($oauthObj, 'errcode')) {
                $Wechat->add(array(
                    'openid'    =>  $openid,
                    'data'  =>  json_encode($oauthObj),
                ));
            }
        }


        $current_url = session('?current_url') ? session('current_url') : U('User/login');
        session('current_url', null);
        redirect($current_url);
    }

    public function login($openid = null) {
        session('openid', $openid);
        $this->redirect(U('Index/index'));
    }
}